<?php

class TaskController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
//            array('allow', // allow all users to perform 'index' and 'view' actions
//                'actions' => array('index', 'view'),
//                'users' => array('*'),
//            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'view', 'create', 'update', 'popView', 'fetchSubcode','fetchClassDes'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => User::model()->getUsers(1),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Task;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Task'])) {
            $model->attributes = $_POST['Task'];

            if ($_POST['Task']['estart']) {
                $model->estart = strtotime($_POST['Task']['estart']);
            }
            if ($_POST['Task']['rstart']) {
                $model->rstart = strtotime($_POST['Task']['rstart']);
            }
            if ($_POST['Task']['eend']) {
                $model->eend = strtotime($_POST['Task']['eend']);
            }
            if ($_POST['Task']['rend']) {
                $model->rend = strtotime($_POST['Task']['rend']);
            }

            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->taskid));
            }
        }

        $criteria = new CDbCriteria;
        $taskClass = Yii::app()->params['classes']['task'];
        $criteria->addCondition('parentid=' . $taskClass);
        $tcodes = Classes::model()->findAll($criteria);
        unset($criteria);
        $tcodeArr = array();        
        foreach ($tcodes as $tcode) {
            if(!$tcodeDefault){
                $tcodeDefault = $tcode['classid'];
            }
            $tcodeArr[$tcode['classid']] = $tcode['classname'];
        };
        
        $criteria = new CDbCriteria;
        $tcodeClass = $tcodeDefault;
        $criteria->addCondition('parentid=' . $tcodeClass);
        $subcodes = Classes::model()->findAll($criteria);
        unset($criteria);
        $subcodeArr = array();
        foreach ($subcodes as $subcode) {
            if(!$subcodeDes){
                $subcodeDes = $subcode['descripiton'];
            }
            $subcodeArr[$subcode['classid']] = $subcode['classname'];
        };

        $this->render('create', array(
            'model' => $model,
            'tcodeArr' => $tcodeArr,
            'subcodeArr' => $subcodeArr,
            'taskDes' => $subcodeDes,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Task'])) {
            $model->attributes = $_POST['Task'];
            if ($_POST['Task']['estart']) {
                $model->estart = strtotime($_POST['Task']['estart']);
            }
            if ($_POST['Task']['rstart']) {
                $model->rstart = strtotime($_POST['Task']['rstart']);
            }
            if ($_POST['Task']['eend']) {
                $model->eend = strtotime($_POST['Task']['eend']);
            }
            if ($_POST['Task']['rend']) {
                $model->rend = strtotime($_POST['Task']['rend']);
            }

            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->taskid));
            }
        }

        if ($model->estart) {
            $model->estart = date('Y-m-d', $model->estart);
        }
        if ($model->rstart) {
            $model->rstart = date('Y-m-d', $model->rstart);
        }
        if ($model->eend) {
            $model->eend = date('Y-m-d', $model->eend);
        }
        if ($model->rend) {
            $model->rend = date('Y-m-d', $model->rend);
        }
        
        $criteria = new CDbCriteria;
        $taskClass = Yii::app()->params['classes']['task'];
        $criteria->addCondition('parentid=' . $taskClass);
        $tcodes = Classes::model()->findAll($criteria);
        unset($criteria);
        $tcodeArr = array();
        foreach ($tcodes as $tcode) {
            $tcodeArr[$tcode['classid']] = $tcode['classname'];
        };
        
        $criteria = new CDbCriteria;
        $tcodeClass = $model->tcode;
        $criteria->addCondition('parentid=' . $tcodeClass);
        $subcodes = Classes::model()->findAll($criteria);
        unset($criteria);
        $subcodeArr = array();
        foreach ($subcodes as $subcode) {
            $subcodeArr[$subcode['classid']] = $subcode['classname'];
        };

        $this->render('update', array(
            'model' => $model,
            'tcodeArr' => $tcodeArr,
            'subcodeArr' => $subcodeArr,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->actionAdmin();
//        $dataProvider = new CActiveDataProvider('Task');
//        $this->render('index', array(
//            'dataProvider' => $dataProvider,
//        ));
    }

    /**
     * Task列表，和list的区别在于，只能看见本office的task
     */
    public function actionTaskList() {

        $criteria = new CDbCriteria;
        $criteria->compare('ptid', $this->ptid);
        return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                ));

        $dataProvider = new CActiveDataProvider('Task');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Task('search');
        $model->unsetAttributes();  // clear any default values

        $session = new CHttpSession;
        $session->open();
        $session['timeFilter'] = array();
        if (isset($_GET['Task'])) {
            $timeFilter['estart1'] = $_GET['estart1'];
            $timeFilter['estart2'] = $_GET['estart2'];
            $timeFilter['eend1'] = $_GET['eend1'];
            $timeFilter['eend2'] = $_GET['eend2'];
            $timeFilter['rstart1'] = $_GET['rstart1'];
            $timeFilter['rstart2'] = $_GET['rstart2'];
            $timeFilter['rend1'] = $_GET['rend1'];
            $timeFilter['rend2'] = $_GET['rend2'];

            $session['timeFilter'] = $timeFilter;
            $model->attributes = $_GET['Task'];
        }
        $this->render('admin', array(
            'model' => $model,
            'timeFilter' => $timeFilter,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Task::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'task-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    //给从task创建Template用的，弹出显示task详细内容
    public function actionPopView($id) {
        $this->layout = 'pop';
        $model = $this->loadModel($id);

        $this->render('popView', array(
            'model' => $model,
        ));
    }

    //获取tcode对应的subcode
    public function actionFetchSubcode() {
        $data = Classes::model()->findAll('parentid=' . (int) $_POST['Task']['tcode']);
//        var_dump( $_POST['Task']['tcode']);
//        exit;
        $data = CHtml::listData($data, 'classid', 'classname');
        echo CHtml::tag('option', array('value' => ''),'请选择', true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }
    
    //获取classes的des
    public function actionFetchClassDes(){
        $data = Classes::model()->find('classid=' . (int) $_POST['classid']);
        echo CJSON::encode(array('success' => true, 'msg' => $data['descripiton']));
    }

}
